<?php
/**
 * 用户模块
 *
 * @author    wangmx <wangmx@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\UserService;

use App\Services\BrandService\BrandToolService;
use App\Services\ImgServices\ImgTool;
use App\Services\ProductsService\ProductTool;
use App\Services\Tool\ImageProcessor\ImagickTool as ImagickTool;
use App\Services\Tool\Message\MessageTool;
use App\Services\Tool\Order\AfterTool;
use App\Services\Tool\Order\OrderTool;
use App\Services\UserService\CCPRestSmsSDK;
use App\Services\UserService\UserTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Log;

class UserService
{
    protected $UserTool;
    protected $ProductsService;
    protected $MessageTool;
    protected $OrderTool;
    protected $AfterTool;

    public function __construct(UserTool $UserTool, ProductTool $Product
        , MessageTool $messageTool, OrderTool $orderTool, AfterTool $afterTool
    )
    {
        $this->UserTool = $UserTool;
        $this->Product = $Product;
        $this->MessageTool = $messageTool;
        $this->OrderTool = $orderTool;
        $this->AfterTool = $afterTool;
    }

    /**
     * 登录/注册/绑定
     * login_type  0平台 1微信 2QQ 3微博
     * access_type 0注册 1登录 2第三方绑定
     * phone  unique_id  udid  identifying
     */
    public function login(Request $request)
    {
        $access_type = $request->get('access_type');
        $phone = $request->get('phone');
        $identifying = $request->get('captcha');
        $udid = $request->get('udid');
        $login_type = $request->get('login_type');
        $unique_id = $request->get('unique_id');

        $checkPhone = $this->UserTool->Type($phone);
        if ($checkPhone == 0 && $login_type == 0) {
            $access_type = 0;
        } else if ($checkPhone == 1 && $login_type == 0) {
            $access_type = 1;
        } else if ($login_type != 0 && strlen($unique_id) > 0) {
            $access_type = 2;
        }

        //检查验证码正确性和时效性
        $checkResult = $this->UserTool->checkIdentifying($phone, $identifying);
        if ($checkResult['state'] != 'M00000') {
            return $checkResult;
        }

        //正则判断手机号
        $checkPhone = $this->UserTool->checkPhone($phone);
        if ($checkPhone == false) {
            $result = array('message' => '这个手机号格式不正确', 'result' => (object)array(), 'state' => 'M09002');
            return $result;
        }

        //验证码正确
        switch ($access_type) {
            case 0: //注册
                $result = self::register($request);
                return $result;
            case 1: //登录
                $checkPhone = $this->UserTool->Type($phone);
                if ($checkPhone == 0) {
                    $result = array('message' => '该手机号未注册,请注册', 'result' => (Object)array(), 'state' => 'M09001');
                    return $result;
                }
                $token = $this->UserTool->getToken();
                $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
                if ($user_id == null) {
                    $result = array('message' => '参数错误', 'result' => (Object)array(), 'state' => 'M00002');
                    return $result;
                }
                DB::table('users')->where('phone', $phone)
                    ->update([
                        'udid' => $udid,
                        'udid_record_time' => time(),
                        'token' => $token,
                        'token_record_time' => time(),
                    ]);
                $this->checkFollowOfficial($user_id);
                $this->UserTool->recordUdid($user_id, $udid);
                $userinfo = DB::table('users')->where('phone', $phone)->select('user_id', 'nick_name', 'original_avatar', 'avatar', 'user_type')->first();
                $userinfo = $this->UserTool->checkHeader($userinfo);
                $result = array('message' => '登录成功', 'result' => $userinfo, 'state' => 'M00000');
                return $result;
            case 2: //绑定
                $result = self::bindPhone($request);
                return $result;
        }
    }

    public function checkFollowOfficial($user_id){
        if($user_id != 10800){
            $check = DB::table('follows')->where(['user_id'=>$user_id,'follow_user_id'=>10800])->first();
            if($check == null){
                DB::table('follows')
                    ->insert(['user_id' => $user_id,
                        'follow_user_id' => 10800,
                        'state' => 1,
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]);
            }
        }
    }
    /**
     * 注册
     */
    public function register(Request $request)
    {
        $phone = $request->get('phone');
        $checkPhone = $this->UserTool->Type($phone);
        if ($checkPhone == 1) {
            $result = array('message' => '该手机号已注册,请直接登录', 'result' => (Object)array(), 'state' => 'M09001');
            return $result;
        }
        $udid = $request->get('udid', '');
        $nick_name = substr_replace($phone, '****', 3, 4);
        $token = $this->UserTool->getToken();
        $avatar = 'Default_avatar.png';
        $original_avatar = 'original_Default_avatar.png';
        $cover_map = 'default_cover_map.png';
        DB::table('users')->insert(
            [
                'phone' => $phone,
                'nick_name' => $nick_name,
                'avatar' => $avatar,
                'original_avatar' => $original_avatar,
                'gender' => 0,
                'birthday' => 0,
                'area' => '',
                'user_type' => 0,
                'login_type' => 0,
                'udid' => $udid,
                'cover_map' => $cover_map,
                'udid_record_time' => time(),
                'token' => $token,
                'token_record_time' => time(),
                'created_at' => time(),
                'updated_at' => time(),
            ]
        );
        $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
        $this->Product->createDefaultCollections($user_id); //创建默认作品集
        $userinfo = DB::table('users')->where('phone', $phone)->select('user_id', 'nick_name', 'avatar', 'original_avatar', 'user_type')->first();
        $this->UserTool->recordUdid($userinfo->user_id, $udid);
        $userinfo = $this->UserTool->checkHeader($userinfo);
        DB::table('follows')
            ->insert(['user_id' => $user_id,
                'follow_user_id' => 10800,
                'state' => 1,
                'created_at' => time(),
                'updated_at' => time(),
            ]);
        $result = array('message' => '注册成功', 'result' => $userinfo, 'state' => 'M00000');
        return $result;
    }

    /**
     * 第三方登录处理
     */
    public function thirdPartyLogin(Request $request)
    {
        $login_type = $request->get('login_type');
        $unique_id = $request->get('unique_id');
        $nick_name = $request->get('nick_name');
        $avatar = $request->get('avatar');
        $udid = $request->get('udid');
        if (empty($unique_id) || strlen($unique_id) == 0 || empty($nick_name) || empty($avatar)) {
            $result = array('message' => '参数不足', 'result' => (Object)array(), 'state' => 'M00002');
            return $result;
        }
        switch ($login_type) {
            case 1: //微信
                $result = $this->UserTool->thirdPartyLoginTool('wechat', 'wechats', $unique_id, $nick_name, $avatar, $udid, $login_type);
                return $result;
                break;
            case 2: //QQ
                $result = $this->UserTool->thirdPartyLoginTool('qq', 'qqs', $unique_id, $nick_name, $avatar, $udid, $login_type);
                return $result;
                break;
            case 3: //微博
                $result = $this->UserTool->thirdPartyLoginTool('weibo', 'weibos', $unique_id, $nick_name, $avatar, $udid, $login_type);
                return $result;
                break;
            default:
                $result = array('message' => '参数不足', 'result' => (Object)array(), 'state' => 'M00002');
                return $result;
        }
    }

    /**
     * 第三方绑定手机
     */
    public function bindPhone(Request $request)
    {
        $login_type = $request->get('login_type');
        $unique_id = $request->get('unique_id');
        $phone = $request->get('phone');
        $udid = $request->get('udid', '');
        if (strlen($login_type) == 0 || strlen($unique_id) == 0 || strlen($phone) == 0) {
            $result = array('message' => '参数不足', 'result' => (Object)array(), 'state' => 'M00002');
            return $result;
        }
        switch ($login_type) {
            case 1: //微信
                $result = $this->UserTool->bindPhoneTool($phone, 'wechat', 'wechats', $login_type, $unique_id, $udid);
                return $result;
                break;
            case 2: //QQ
                $result = $this->UserTool->bindPhoneTool($phone, 'qq', 'qqs', $login_type, $unique_id, $udid);
                return $result;
                break;
            case 3: //微博
                $result = $this->UserTool->bindPhoneTool($phone, 'weibo', 'weibos', $login_type, $unique_id, $udid);
                return $result;
                break;
            default:
                $result = array('message' => '参数错误', 'result' => (Object)array(), 'state' => 'M00002');
                return $result;
        }
    }

    /**
     * 用户信息
     */
    public function userInfo(Request $request)
    {
        $user_id = $request->get('user_id');
        if (strlen($user_id) == 0 || $user_id == 0) {
            $result = array('message' => '请先登录', 'result' => (Object)array(), 'state' => 'M09000');
            return $result;
        }
        $userinfo = DB::table('users')->where('user_id', $user_id)
            ->select('user_id', 'phone', 'nick_name', 'original_avatar', 'avatar', 'gender', 'birthday', 'area', 'user_type')
            ->first();
        if ($userinfo == null) {
            $result = array('message' => '用户不存在', 'result' => (Object)array(), 'state' => 'M09005');
            return $result;
        }
        $hasBind = $this->UserTool->hasBind($user_id); //检查第三方绑定
        $userinfo->hasBind = $hasBind;
        if ($userinfo->birthday != 0) {
            $userinfo->birthday = date('Y-m-d', $userinfo->birthday);
        } else {
            $userinfo->birthday = '';
        }
        $fans_num = $this->UserTool->fansNum($user_id);

        //作品数
        $product_num = $this->Product->getProductNumByUserID($user_id);

        //待付款
        $wait_pay = $this->OrderTool->get_order_state_count($user_id, 'unpay');

        //待发货
        $wait_send = $this->OrderTool->get_order_state_count($user_id, 'unsend');

        //待收货
        $wait_rejected = $this->OrderTool->get_order_state_count($user_id, 'unsign');
        //未读信息
        $register_time = $this->UserTool->registerTime($user_id);
        $message_data = $this->MessageTool->getAllMessageCount(['user_id' => $user_id, 'created_at' => $register_time]);

        //售后
        $after_sales = $this->AfterTool->get_user_aftermark_number($user_id);

        //设计师认证状态
        $designerState = $this->UserTool->checkAuthenticationToDesigner($user_id);

        //品牌认证状态
        $authentication_tag_img = asset('images/authenticationTagByUserinfo.png');
        $brandState = $this->UserTool->checkAuthenticationToBrand($user_id);
        $userinfo->designer_state = $designerState; //0未审核 1已通过 2被拒绝 3未填写提交
        $userinfo->brand_state = $brandState; //0未审核 1已通过 2被拒绝 3未填写提交
        $userinfo = $this->UserTool->checkHeader($userinfo); //检查头像是否需要拼接
        $userinfo->product_num = $product_num;
        $userinfo->fans_num = $fans_num;
        $userinfo->wait_pay_num = $wait_pay;
        $userinfo->wait_send_num = $wait_send;
        $userinfo->wait_rejected_num = $wait_rejected;
        $userinfo->message_data_num = $message_data;
        $userinfo->after_sales_num = $after_sales;
        if ($designerState == 1 || $brandState == 1) {
            $userinfo->authentication_tag_img = $authentication_tag_img;
        } else {
            $userinfo->authentication_tag_img = "";
        }
        $result = array('message' => '用户信息', 'result' => $userinfo, 'state' => 'M00000');
        return $result;
    }

    /**
     * 平台绑定第三方
     */
    public function bindThirdParty(Request $request)
    {
        $user_id = $request->get('user_id');
        $bind_type = $request->get('bind_type'); //1微信 2QQ 3微博
        $unique_id = $request->get('unique_id');
        $nick_name = $request->get('nick_name');
        $avatar = $request->get('avatar');
        if (empty($user_id) || empty($bind_type) || empty($unique_id)) {
            $result = array('message' => '参数错误', 'result' => (Object)array(), 'state' => 'M09001');
            return $result;
        }
        if ($bind_type == 1) {
            $type = 'wechat';
            $DBtype = 'wechats';
        } else if ($bind_type == 2) {
            $type = 'qq';
            $DBtype = 'qqs';
        } else if ($bind_type == 3) {
            $type = 'weibo';
            $DBtype = 'weibos';
        } else {
            $result = array('message' => '参数错误', 'result' => (Object)array(), 'state' => 'M09001');
            return $result;
        }
        $result = $this->UserTool->bindThirdPartyTool($user_id, $type, $DBtype, $unique_id, $nick_name, $avatar, $bind_type);
        return $result;
    }

    /**
     * 解绑第三方
     */
    public function cancelBindThirdParty(Request $request)
    {
        $user_id = $request->get('user_id');
        $bind_type = $request->get('bind_type'); //1微信 2QQ 3微博
        $type = '';
        $DBtype = '';
        if ($bind_type == 1) {
            $type = 'wechat';
            $DBtype = 'wechats';
        } else if ($bind_type == 2) {
            $type = 'qq';
            $DBtype = 'qqs';
        } else if ($bind_type == 3) {
            $type = 'weibo';
            $DBtype = 'weibos';
        }
        $bindID = DB::table('users')->where('user_id', $user_id)->value($type);
        DB::table('users')->where('user_id', $user_id)->update([$type => 0, 'updated_at' => time()]);
        DB::table($DBtype)->where('id', $bindID)->update(['state' => 0, 'updated_at' => time()]);
        $data = array('hasBind' => array($type => 0));
        $result = array('message' => '解绑成功', 'result' => $data, 'state' => 'M00000');
        return $result;
    }

    /**
     * 获取国家
     */
    public function country()
    {
        $countryLists = DB::table('countrys')->where('state', 1)->select('country_id', 'country_name', 'area_code')->get();
        foreach ($countryLists as $country) {
            $country_name = $country->country_name;
            $snameFirstChar = $this->UserTool->getFirstCharter($country_name); //取出第一个汉字的首字母
            $list[$snameFirstChar][] = $country; //已首字母做KEY
        }
        ksort($list); //降序
        $result = array('message' => '国家区号列表', 'result' => $list, 'state' => 'M00000');
        return $result;
    }

    /**
     * 发送验证码
     * phone,send_type,login_type
     * 普通登录 传phone send_type = 0 login_type = 0
     * 第三方登录 传phone send_type = 1 login_type = 1 2 3
     */
    public function sendTemplateSMS(Request $request)
    {
        $country = $request->get('country');
        $phone = $request->input('phone');
        if (empty($phone)) {
            $result = array('message' => '手机号码不能为空', 'result' => (object)array(), 'state' => 'M09006');
            return $result;
        }
        $send_type = $request->get('send_type', 0);
        $login_type = $request->get('login_type');
        if ($send_type == 1) {
            switch ($login_type) {
                case 1: //微信
                    $checkResult = $this->UserTool->checkBindBySendCode('wechat', $phone);
                    if ($checkResult == true) {
                        $result = array('message' => '该手机号码已绑定微信账号', 'result' => (object)array(), 'state' => 'M09006');
                        return $result;
                    }
                    break;
                case 2: //QQ
                    $checkResult = $this->UserTool->checkBindBySendCode('qq', $phone);
                    if ($checkResult == true) {
                        $result = array('message' => '该手机号码已绑定QQ账号', 'result' => (object)array(), 'state' => 'M09007');
                        return $result;
                    }
                    break;
                case 3: //微博
                    $checkResult = $this->UserTool->checkBindBySendCode('weibo', $phone);
                    if ($checkResult == true) {
                        $result = array('message' => '该手机号码已绑定微博账号', 'result' => (object)array(), 'state' => 'M09008');
                        return $result;
                    }
                    break;
            }
        }
        $accountSid = env('accountSid');
        //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
        $accountToken = env('accountToken');
        //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
        //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
        $appId = env('appId');
        //请求地址
        //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
        //生产环境（用户应用上线使用）：app.cloopen.com
        //        $serverIP = 'app.cloopen.com';
        $serverIP = 'sandboxapp.cloopen.com';
        //请求端口，生产环境和沙盒环境一致
        $serverPort = '8883';
        //REST版本号，在官网文档REST介绍中获得。
        $softVersion = '2013-12-26';
        // 初始化REST SDK
        $rest = new CCPRestSmsSDK($serverIP, $serverPort, $softVersion);
        $rest->setAccount($accountSid, $accountToken);
        $rest->setAppId($appId);
        $random = $rest->random(4);
        $time = time();
        $datas = array("$random", "1"); //发送给用户的验证码 和 有效时间
        // 发送模板短信
        $to = $request->input('phone');
        $checkphone = $this->UserTool->checkPhone($to);
        if ($checkphone == false) {
            $result = array('message' => '这个手机号格式不正确', 'result' => (object)array(), 'state' => 'M09002');
            return $result;
        }
        $tempId = env('tempId');
        $result = $rest->sendTemplateSMS($to, $datas, $tempId);
        $code = $result->statusCode;
        $codes = json_decode($code);
        $access_type = $this->UserTool->Type($to);
        if ($send_type == 1) {
            $access_type = 2;
        }
        $hasPhone = DB::table('identifyings')->where('phone', $to)->first();
        if ($hasPhone != null) {
            $time = DB::table('identifyings')->where('phone', $to)->value('created_at');
            $diffTime = time() - $time;
            if ($diffTime < 60) {
//验证短信验证码是否1分钟内
                $arr = array('message' => '验证码已发送,请查看短信', 'result' => (Object)array(), 'state' => 'M09004');
                return $arr;
            }
        }
        if ($codes == 160040) {
            $arr = array('message' => '你的验证次数已达上限，明天再来吧', 'result' => (Object)array(), 'state' => 'M09003');
            return $arr;
        }
        if ($codes == 000000) {
            DB::table('identifyings')->where('phone', $phone)->delete();
            DB::table('identifyings')->insert(
                array(
                    'identifying' => $random,
                    'phone' => $to,
                    'created_at' => time(),
                    'updated_at' => time(),
                )
            );
            $result = array(
                'access_type' => $access_type);
            $arr = array('message' => '验证码发送成功', 'result' => $result, 'state' => 'M00000');
            return $arr;
        } else {
            $arr = array('message' => '服务器维护中，请稍等', 'result' => (Object)array(), 'state' => 'M01001');
            return $arr;
        }
    }

    //修改昵称
    public function changeName(Request $request)
    {
        $user_id = $request->input('user_id');
        $nick_name = $this->UserTool->trimall($request->input('nick_name'));
        if (!preg_match("/[\x{4e00}-\x{9fa5}\w]+$/u", $nick_name) ||
            preg_match("/(\\\u[ed][0-9a-f]{3})/i", json_encode($nick_name)) != 0
        ) {
            //不允许特殊字符  后一个正则为判断emoji表情
            $arr = array('message' => '昵称中不能含有特殊字符', 'result' => (object)array(), 'state' => 'M09009');
            return $arr;
        }

        $checkname = $this->UserTool->checkCompanyName($nick_name);
        if ($checkname == true) {
            $arr = array('message' => $nick_name . ' 不能被设为昵称', 'result' => (object)array(), 'state' => 'M09009');
            return $arr;
        }

        if (mb_strlen($nick_name) > 13) {
            $arr = array('message' => '只能输入6个汉字或12个英文以内的字符', 'result' => (object)array(), 'state' => 'M09009');
            return $arr;
        }

        $has = DB::table('users')->whereNotIn('user_id', [$user_id])->where('nick_name', $nick_name)->first();
        if ($has != null) {
            $arr = array('message' => '该昵称已存在,请重新输入', 'result' => (object)array(), 'state' => 'M09010');
            return $arr;
        }
        DB::table('users')
            ->where('user_id', $user_id)
            ->update(
                [
                    'nick_name' => $nick_name,
                    'updated_at' => time(),
                ]
            );

        $result = array('nick_name' => $nick_name);
        $arr = array('message' => '修改成功', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    //修改头像
    public function changeHeaderimg(Request $request)
    {
        $ImgTool = new ImgTool(new ImagickTool());
        $user_id = $request->input('user_id');
        $user_type = DB::table('users')->where('user_id', $user_id)->value('user_type');
        $avatar = $request->file('avatar');
        if (empty($avatar)) {
            $arr = array('message' => '请先选择图片', 'result' => (Object)array(), 'state' => 'M00000');
            return $arr;
        }
        //主图
        $original_avatar_path = $ImgTool->imgSave($avatar, 2, true);
        //生成头像缩略图
        $avatarUrl = $ImgTool->getImgThumbByImgPath($original_avatar_path, 300, 300, true);

        DB::table('users')
            ->where('user_id', $user_id)
            ->update(
                [
                    'original_avatar' => $original_avatar_path,
                    'avatar' => $avatarUrl,
                    'updated_at' => time(),
                ]
            );
        if ($user_type == 2) {
//品牌商
            $BrandToolService = new BrandToolService();
            $data = array('user_id' => $user_id, 'avatar' => $avatarUrl, 'state' => 1);
            $BrandToolService->syncBrandUser($data); //同步信息到品牌
        }
        $avatarUrl = ImgTool::getImgUrlByImgPath($avatarUrl);
        $result = array('avatar' => $avatarUrl);
        $arr = array('message' => '修改成功', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    //修改性别
    public function changeGender(Request $request)
    {
        $user_id = $request->input('user_id');
        $gender = $request->input('gender');
        DB::table('users')
            ->where('user_id', $user_id)
            ->update(
                [
                    'gender' => $gender,
                    'updated_at' => time(),
                ]
            );

        $result = array('gender' => $gender);
        $arr = array('message' => '修改成功', 'result' => $result, 'state' => 'M00000');
        return $arr;

    }

    //修改生日
    public function changeBirthday(Request $request)
    {
        $user_id = $request->get('user_id');
        $birthday = $request->get('birthday');
        if ($birthday != '') {
            $time = strtotime($birthday);
            DB::table('users')
                ->where('user_id', $user_id)
                ->update(
                    [
                        'birthday' => $time,
                        'updated_at' => time(),
                    ]
                );
            $birthday = date('Y-m-d', $time);
        } else {
            $birthday = DB::table('users')->where('user_id', $user_id)->value('birthday');
            $birthday = date('Y-m-d', $birthday);
        }
        $result = array('birthday' => $birthday);
        $arr = array('message' => '修改成功', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    //修改区域
    public function changeArea(Request $request)
    {
        $user_id = $request->input('user_id');
        $area = $request->input('area');
        DB::table('users')
            ->where('user_id', $user_id)
            ->update(
                [
                    'area' => $area,
                    'updated_at' => time(),
                ]
            );
        $result = array('area' => $area);
        $arr = array('message' => '修改成功', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    /**
     * 关注 取消关注
     */
    public function follow(Request $request)
    {
        $user_id = $request->get('user_id'); //当前用户ID
        if (empty($user_id) || $user_id == 0) {
            $result = array('message' => '请先登录', 'result' => (object)array(), 'state' => 'M09011');
            return $result;
        }
        $follow_user_id = $request->get('follow_user_id'); //关注人ID
        $hasfollow = DB::table('follows')->where(['user_id' => $user_id, 'follow_user_id' => $follow_user_id])->first();
        if ($hasfollow == null) {
            if ($user_id == $follow_user_id) {
                $result = array('message' => '你每时每刻都关注着自己', 'result' => (object)array(), 'state' => 'M09011');
                return $result;
            }
            DB::table('follows')->insert([
                'user_id' => $user_id,
                'follow_user_id' => $follow_user_id,
                'state' => 1,
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $user_type = DB::table('users')->where('user_id', $follow_user_id)->value('user_type');
            $count = DB::table('follows')->where(['follow_user_id' => $follow_user_id, 'state' => 1])->count();
            if ($user_type == 1) {
//设计师
                DB::table('designer_authentications')->where('user_id', $follow_user_id)->update([
                    'fans_num' => $count,
                ]);
            } else if ($user_type == 2) {
//品牌商
                DB::table('brand_authentications')->where('user_id', $follow_user_id)->update([
                    'fans_num' => $count,
                ]);
            }
            $data = array('follow_type' => 1);
            $result = array('message' => '关注成功', 'result' => $data, 'state' => 'M00000');
            return $result;
        } else {
//            if($follow_user_id == 10800){
            //                $result = array('message' => '官方账号不能取关哦~', 'result' => (object)array(), 'state' => 'M00000');
            //                return $result;
            //            }
            DB::table('follows')->where(['user_id' => $user_id, 'follow_user_id' => $follow_user_id])->delete();
            $user_type = DB::table('users')->where('user_id', $follow_user_id)->value('user_type');
            $count = DB::table('follows')->where(['follow_user_id' => $follow_user_id, 'state' => 1])->count();
            if ($user_type == 1) {
//设计师
                DB::table('designer_authentications')->where('user_id', $follow_user_id)->update([
                    'fans_num' => $count,
                ]);
            } else if ($user_type == 2) {
//品牌商
                DB::table('brand_authentications')->where('user_id', $follow_user_id)->update([
                    'fans_num' => $count,
                ]);
            }
            $data = array('follow_type' => 0);
            $result = array('message' => '你已取消关注', 'result' => $data, 'state' => 'M00000');
            return $result;
        }
    }

    /**
     * 关注列表 我的关注
     */
    public function followList(Request $request)
    {
        $user_id = $request->get('user_id');
        $useridlist = DB::table('follows')->where('user_id', $user_id)->distinct()->pluck('follow_user_id');
        $userinfos = DB::table('users')->whereIn('user_id', $useridlist)->where('user_type', '<>', 0)->select('user_id', 'nick_name', 'original_avatar', 'avatar', 'is_official')->get();
        if (count($userinfos) == 0) {
            $result = array('message' => '我的关注', 'result' => (Object)array(), 'state' => 'M00000');
            return $result;
        }
        foreach ($userinfos as $item) {
            $item = $this->UserTool->checkHeader($item);
            $item->product_num = $this->Product->getProductNumByUserID($item->user_id);
            $item->fans_num = $this->UserTool->fansNum($item->user_id);
            $item->user_type = $this->UserTool->userType($item->user_id);
            $nick_name = $item->nick_name;
            $snameFirstChar = $this->UserTool->getFirstCharter($nick_name); //取出第一个汉字的首字母
            $list[$snameFirstChar][] = $item; //已首字母做KEY
        }
        ksort($list); //降序
        $result = array('message' => '我的关注', 'result' => $list, 'state' => 'M00000');
        return $result;
    }

    /**
     * 更新封面图 设计师 品牌可用
     */
    public function changeCoverMap(Request $request)
    {
        $ImgTool = new ImgTool(new ImagickTool());
        $user_id = $request->input('user_id');
        $cover_map = $request->file('cover_map');
        if (empty($cover_map)) {
            $arr = array('message' => '请选择图片', 'result' => (Object)array(), 'state' => 'M00000');
            return $arr;
        }
        $cover_mapUrl = $ImgTool->imgSave($cover_map, 2, true);
        DB::table('users')
            ->where('user_id', $user_id)
            ->update(
                [
                    'cover_map' => $cover_mapUrl,
                    'updated_at' => time(),
                ]
            );
        $cover_mapUrl = ImgTool::getImgUrlByImgPath($cover_mapUrl);
        $result = array('cover_map' => $cover_mapUrl);
        $arr = array('message' => '更新成功', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    /**
     * 获取用户认证信息 设计师
     */
    public function getAuthenticationDesigner(Request $request)
    {
        $user_id = $request->get('user_id');
        $result = $this->UserTool->getAuthenticationToDesigner($user_id);
        $arr = array('message' => '设计师认证信息', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    /**
     * 获取用户认证信息 品牌
     */
    public function getAuthenticationBrand(Request $request)
    {
        $user_id = $request->get('user_id');
        $result = $this->UserTool->getAuthenticationToBrand($user_id);
        $arr = array('message' => '品牌认证信息', 'result' => $result, 'state' => 'M00000');
        return $arr;
    }

    /**
     * 个人主页
     */
    public function personCenter(Request $request)
    {
        $per_page = $request->get('per_page');
        if (empty($per_page)) {
            $per_page = 10;
        }
        $query_user_id = $request->get('query_user_id'); //查询的USER_ID
        $current_user_id = $request->get('user_id'); //当前USER_ID

        $products = $this->Product->getProductsByUserId($query_user_id, $per_page, $current_user_id);
        $user_type = DB::table('users')->where('user_id', $query_user_id)->value('user_type');
        if ($user_type == 0) {
            $arr = array('message' => '非认证用户', 'result' => (Object)array(), 'state' => 'M09001');
            return $arr;
        }
        $job = '';
        $user_name = '';
        $company = '';
        $sales_num = '';
        if ($user_type == 1) {
            $check = DB::table('designer_authentications')->where(['user_id' => $query_user_id, 'state' => 1])->first();
            if ($check == null) {
                $arr = array('message' => '非认证用户', 'result' => (Object)array(), 'state' => 'M09001');
                return $arr;
            }
            $authentication_info = DB::table('designer_authentications')->where('user_id', $query_user_id)
                ->select('user_id', 'real_name', 'gender', 'job', 'card_id', 'phone', 'email', 'company', 'sales_num')
                ->first();
            $company = $authentication_info->company;
            $job = $authentication_info->job;
            $user_name = $authentication_info->real_name;
            $sales_num = $authentication_info->sales_num;
        }
        if ($user_type == 2) {
            $check = DB::table('brand_authentications')->where(['user_id' => $query_user_id, 'state' => 1])->first();
            if ($check == null) {
                $arr = array('message' => '非认证用户', 'result' => (Object)array(), 'state' => 'M09001');
                return $arr;
            }
            $authentication_info = DB::table('brand_authentications')->where('user_id', $query_user_id)
                ->select('user_id', 'company_name', 'company_abbreviation', 'manager_name', 'job', 'sales_num')->first();
            $company = $authentication_info->company_name;
            $job = $authentication_info->job;
            $user_name = $authentication_info->company_abbreviation;
            $sales_num = $authentication_info->sales_num;
        }
        $is_follow = $this->UserTool->is_follow($current_user_id, $query_user_id);
        $product_num = $this->Product->getProductNumByUserID($query_user_id, $current_user_id);
        $avatar = $this->UserTool->headerimgByid($query_user_id); //头像
        $cover_map = $this->UserTool->coverMap($query_user_id); //封面图
        $fans_num = $this->UserTool->fansNum($query_user_id); //封面图
        $is_official = DB::table('users')->where('user_id',$query_user_id)->value('is_official');
        $detail = (Object)array();
        $detail->total_page = $products['total_page']; //总页数
        $detail->per_page = $products['per_page']; //一页显示条数
        $detail->current_page = $products['current_page']; //当前页数
        $detail->user_id = $query_user_id; //查询的USER_ID
        $detail->cover_map = $cover_map; //封面图
        $detail->avatar = $avatar; //头像
        $detail->is_follow = $is_follow; //是否关注
        $detail->is_official = $is_official; //是否关注
        $detail->sales_num = $sales_num; //销量
        $detail->fans_num = $fans_num; //粉丝数
        $detail->company = $company; //公司名
        $detail->job = $job; //职位
        $detail->nick_name = $user_name; //昵称
        $detail->product_num = $product_num; //作品数
        $authentication_tag_img = asset('images/authenticationTag.png');
        $detail->authentication_tag_img = $authentication_tag_img; //认证标签图片
        $detail->products = $products['data'];

        $arr = array('message' => '个人中心', 'result' => $detail, 'state' => 'M00000');
        return $arr;
    }

    //验证码测试
    public function sendCaptcha(Request $request)
    {
        $phone = $request->get('phone');
        $random = $this->UserTool->random(4);
        $hasPhone = DB::table('identifyings')->where('phone', $phone)->first();
        if ($hasPhone == null) {
            DB::table('identifyings')->insert(
                array(
                    'identifying' => $random,
                    'phone' => $phone,
                    'created_at' => time(),
                    'updated_at' => time(),
                )
            );
        } else {
            DB::table('identifyings')->where('phone', $phone)->update(
                array(
                    'identifying' => $random,
                    'phone' => $phone,
                    'created_at' => time(),
                    'updated_at' => time(),
                )
            );
        }
        $access_type = $this->UserTool->Type($phone);
        $result = array(
            'access_type' => $access_type, 'captcha' => $random);
        $arr = array('message' => '成功', 'result' => $result, 'state' => 'M00000');
        return $result;
    }

    /**
     * 验证登录状态
     */
    public function checkLoginState(Request $request)
    {
        $user_id = $request->get('user_id');
        $current_udid = $request->get('udid');
        $DB_user_udid = DB::table('users')->where('user_id', $user_id)->value('udid');
        if ($current_udid != $DB_user_udid) {
            $login_time = DB::table('user_udids')->where(['user_id' => $user_id, 'udid' => $DB_user_udid])->value('login_time');
            $date = date("Y年m月d日 H时i分s秒", $login_time);
            $result = array('message' => '您的账号于' . $date . '在异地登录', 'result' => (Object)array(), 'state' => 'M10002');
            return $result;
        }
        $DB_token = DB::table('users')->where('user_id', $user_id)->value('token');
        $DB_token_time = DB::table('users')->where('user_id', $user_id)->value('token_record_time');
        $diff_day = (time() - $DB_token_time) / 86400;
        if ($diff_day > 15) {
            $result = array('message' => '登录超时,请重新登录', 'result' => (Object)array(), 'state' => 'M10001');
            return $result;
        }
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        $user_id = $request->get('user_id');
        DB::table('users')->where('user_id', $user_id)->update(
            [
                'udid' => '',
                'udid_record_time' => 0,
                'token' => '',
                'token_record_time' => 0,
            ]
        );
        $result = array('message' => '退出登录成功', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * @param $name
     * @return bool
     * 检查参数是否存在
     */
    public function issetCheck($name, $path, $user_id)
    {
        $data = isset($name) ? $name : 0;
        return $data;
    }

    /**
     * @return string
     * 脚本  批量创建默认作品集
     */
    public function createCollections()
    {
        $list = DB::table('users')->select('user_id')->get()->toArray();
        foreach ($list as $item) {
            $user_id = $item->user_id;
            $check = DB::table('user_collections')->where('user_id', $user_id)->where('is_default', 1)->first();
            if ($check == null) {
                $this->Product->createDefaultCollections($user_id); //创建默认作品集
            }
        }
        return 'success';
    }

    /**
     * mytee微信根据手机号码获取user_id,没有注册自动注册
     */
    public function checkMobile(Request $request)
    {
//        $phone = $request->get('mobile');
//        $info = DB::table('users')->where('phone', $phone)->first();
//        if ($info == null) {
//            $udid = $request->get('udid', '');
//            $nick_name = substr_replace($phone, '****', 3, 4);
//            $token = $this->UserTool->getToken();
//            $avatar = 'Default_avatar.png';
//            $original_avatar = 'original_Default_avatar.png';
//            $cover_map = 'default_cover_map.png';
//            DB::table('users')->insert(
//                [
//                    'phone' => $phone,
//                    'nick_name' => $nick_name,
//                    'avatar' => $avatar,
//                    'original_avatar' => $original_avatar,
//                    'gender' => 0,
//                    'birthday' => 0,
//                    'area' => '',
//                    'user_type' => 0,
//                    'login_type' => 0,
//                    'udid' => $udid,
//                    'cover_map' => $cover_map,
//                    'udid_record_time' => time(),
//                    'token' => $token,
//                    'token_record_time' => time(),
//                    'created_at' => time(),
//                    'updated_at' => time(),
//                ]
//            );
//            $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
//            $this->Product->createDefaultCollections($user_id); //创建默认作品集
//        }
//        $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
//        return $user_id;
    }


    public function userRegister(Request $request)
    {
        $phone = $request->get('phone');
        $unique_id = $request->get('unique_id');
        $nick_name = $request->get('nick_name');
        $avatar = $request->get('avatar');
        $check_wechat = DB::table('wechats')->where('unique_id', $unique_id)->first();
        if ($check_wechat == null) {
            $wechat_id = DB::table('wechats')->insertGetId(
                [
                    'unique_id' => $unique_id,
                    'nick_name' => $nick_name,
                    'avatar' => $avatar,
                    'state' => 0,
                    'created_at' => time(),
                    'updated_at' => time()
                ]
            );
            $info = DB::table('users')->where('phone', $phone)->first();
            if ($info == null) {
                $udid = $request->get('udid', '');
                $nick_name = substr_replace($phone, '****', 3, 4);
                $token = $this->UserTool->getToken();
                $avatar = 'Default_avatar.png';
                $original_avatar = 'original_Default_avatar.png';
                $cover_map = 'default_cover_map.png';
                DB::table('users')->insert(
                    [
                        'phone' => $phone,
                        'nick_name' => $nick_name,
                        'avatar' => $avatar,
                        'original_avatar' => $original_avatar,
                        'gender' => 0,
                        'birthday' => 0,
                        'area' => '',
                        'user_type' => 0,
                        'login_type' => 1,
                        'udid' => $udid,
                        'cover_map' => $cover_map,
                        'udid_record_time' => time(),
                        'token' => $token,
                        'token_record_time' => time(),
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]
                );
                $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
                $this->Product->createDefaultCollections($user_id); //创建默认作品集
            }
        }


        $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
        return $user_id;
    }
}
